package com.rajaev.dtu.tractor.domain.repository.mongo;

import cn.hutool.core.date.DateUtil;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.rajaev.dtu.tractor.domain.entity.ElectricityDto;
import com.rajaev.dtu.tractor.infrastructure.helper.MongoDbUtils;
import com.rajaev.dtu.tractor.interfaces.assembler.AssemblerFactory;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Repository
public class DeviceElectricityRepository {

    @Autowired
    private MongoDbUtils mongoDbUtils;

    private static final String collection_name = "electricityMessage";

    public void saveElectricityRecord(Integer electricOrderId, BigDecimal totalA, BigDecimal totalV, String vin, long messageTimestamp) {
        Document document = new Document();
        document.put("vin", vin);
        document.put("electricOrderId", electricOrderId);
        document.put("createAt", messageTimestamp);
        document.put("date", DateUtil.format(new Date(messageTimestamp * 1000), "yyyyMMdd"));
        document.put("totalA", totalA.setScale(2, BigDecimal.ROUND_DOWN).floatValue());
        document.put("totalV", totalV.setScale(2, BigDecimal.ROUND_DOWN).floatValue());
        mongoDbUtils.getDatabase().getCollection(collection_name).insertOne(document);
    }

    public List<ElectricityDto> selectElectricRecordByOrderId(Integer id) {
        MongoCursor<Document> mongoCursor = mongoDbUtils.getDatabase().getCollection(collection_name)
                .find(Filters.eq("electricOrderId", id))
                .sort(Sorts.descending("createAt"))
                .iterator();
        List<ElectricityDto> electricityDtoList = new LinkedList<>();
        AssemblerFactory assemblerFactory = new AssemblerFactory();
        while (mongoCursor.hasNext()) {
            Document document = mongoCursor.next();
            ElectricityDto electricityDto = assemblerFactory.convert((source, target) -> {
                target.setElectricOrderId(document.getInteger("electricOrderId"));
                target.setCreateAt(document.getLong("createAt"));
                target.setTotalV(document.getDouble("totalV"));
                target.setTotalA(document.getDouble("totalA"));
                target.setDate(document.getString("date"));
                target.setVin(document.getString("vin"));
            }, document, ElectricityDto.class);
            electricityDtoList.add(electricityDto);
        }
        return electricityDtoList;
    }

}
